<?php

namespace backend\controllers;

use Yii;
use backend\models\BuildCity;
use backend\models\BuildCitySearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\models\City;
use yii\web\ForbiddenHttpException;
use backend\models\AdminInfo;
use backend\models\OperatorRelation;
use backend\models\GrpCity;

/**
 * BuildCityController implements the CRUD actions for BuildCity model.
 */
class BuildCityController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }
    public function beforeAction($action)
    {
    	//如果未登录，则直接跳转
    	if(Yii::$app->user->isGuest){
    		return $this->redirect(['/site/login']);
    	}
    	$action = Yii::$app->controller->action->id;
    	$controller = Yii::$app->controller->id;
    	$login_id = Yii::$app->user->identity->id;
    	if(\Yii::$app->user->can('build-city')){
    		if($action == 'create' && AdminInfo::check_create('create') == true){
				return true;
			}
    		if($this->_access($action) == true){
    			return true;
    		}
    		$id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
    		if($id != 0){
    			$model = $this->findModel($id);
    			
				if($action == 'view' && AdminInfo::check_user_id($login_id,$model['admin_id'],'view')){
    				return true;
    			}elseif (in_array($action, array('update','delete')) && AdminInfo::check_user_id($login_id,$model['admin_id'],'edit')){
    				return true;
    			}else{
    				throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
    			}
    		}
    	}else{
    		throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission !'));
    	}
    }
    //允许访问
    function _access($action){
    	$action_list = array(
    			'index',
    			'select-province-id',
    	    'select-city',
    	    'update',
    	    'getbulidlist'
    	);
    	if(in_array($action, $action_list)){
    		return true;
    	}
    }

    /**
     * Lists all BuildCity models.
     * @return mixed
     */
    public function actionIndex()
    {
        
        
        $searchModel = new BuildCitySearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    /**
     * Displays a single BuildCity model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new BuildCity model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new BuildCity();
        if ($model->load(Yii::$app->request->post())) {    
            $post=Yii::$app->request->post();
        	$model->admin_id = Yii::$app->user->identity->id;
        	if(key_exists("OperatorRelation", $post)){
        	    $model->city_id=$post['OperatorRelation']['city_list'][0];
        	}
        	$model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }
    /*
     *根据城市获取小区 
     */
    public function actionGetbulidlist(){
        $cityid=Yii::$app->request->post()['cityid'];
        $bids = BuildCity::find()->where("city_id =:cityid",array(":cityid"=>$cityid))->asArray()->all();
        echo json_encode($bids);exit();
    }
    /**
     * Updates an existing BuildCity model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {  	
        $model = $this->findModel($id);
        $login_id = Yii::$app->user->identity->id;
        $admin_id = $model['admin_id'];
       /*  if(AdminInfo::check_hasoperator($login_id, $admin_id,'edit'))
        { */
	        $prefix_province_id = substr($model->city_id, 0, 2);
	        $model->province_id = $prefix_province_id.'0000';//省份id
	        $city = City::findBySql("select * from grp_city where id like '$prefix_province_id%00'")->all();
	        if ($model->load(Yii::$app->request->post())   ) {
	            $post=Yii::$app->request->post();
	            if(key_exists("OperatorRelation", $post)){
	                $model->city_id=$post['OperatorRelation']['city_list'][0];
	            }
	           
	            $model->save();
	            return $this->redirect(['view', 'id' => $model->id]);
	        } else {
	            return $this->render('update', [
	                'model' => $model,
	            	'city'=>$city,//列表
	            ]);
	        }
       /*  }else{
        	throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
        } */
    }

    /**
     * Deletes an existing BuildCity model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the BuildCity model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return BuildCity the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
    	//运营商查看修改自己的单子
    	$model = BuildCity::findOne($id);    	
        if ($model !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
        
    public function actionSelectProvinceId($province_id){
			
    	$result = City::select_province($province_id);
    	$option = '';
    	 
    	if ($result) {
    		foreach ($result as $value) {
    			$option .= '<option value="' . $value['id'] . '">' . $value['name'] . '</option>';
    		}
    	} else {
    		$option .= '<option value="0">暂无</option>';
    	}
    	echo $option; 	 
    }
    /**
     * 根据省份获取该运营商的城市列表
     * @param   $province_id
     */
    public function actionSelectCity(){
        $user_type=intval(Yii::$app->user->identity->user_type);
        $province_id=Yii::$app->request->post("province_id");
        if($user_type>1){//运营商
            $cityList=OperatorRelation::getCitylistByIdAndProvince($province_id);
        }else{
            $specilProvince=array('110000','120000','310000','500000');
            if(in_array($province_id, $specilProvince)){
             //   $cityList=GrpCity::area2($province_id);
                $cityList=GrpCity::findBySql("select * from grp_city where id=:id",array(":id"=>$province_id))->asArray()->all();
            }else{
                $cityList=GrpCity::city($province_id);
            }
        }
        echo json_encode($cityList);exit();
        
    }
}
